package com.sunda.spmswms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmscommon.feign.IFeignServiceCommon;
import com.sunda.spmswms.entity.*;
import com.sunda.spmswms.mapper.SapPackageBoxMapper;
import com.sunda.spmswms.mapper.SapPackageListDtlMapper;
import com.sunda.spmswms.mapper.SapPackageListMapper;
import com.sunda.spmswms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.sunda.spmscommon.Constans.*;

/**
 * <p>
 * SAP装箱单表抬头 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-04-22
 */
@Service
public class SapPackageListServiceImpl extends ServiceImpl<SapPackageListMapper, SapPackageList> implements ISapPackageListService {

    @Autowired
    ISapPackageListDtlService iSapPackageListDtlService;

    @Autowired
    IWhsOutService iWhsOutService;

    @Autowired
    ISapPackageBoxService iSapPackageBoxService;

    @Autowired
    ISapDeliveryNoteLogService iSapDeliveryNoteLogService;

    @Autowired
    IFeignServiceCommon iFeignServiceCommon;

    @Autowired
    SapPackageListDtlMapper sapPackageListDtlMapper;

    @Autowired
    SapPackageBoxMapper sapPackageBoxMapper;

    @Autowired
    ISapBoxNoteService iSapBoxNoteService;

    @Override
    public List<Map<String, Object>> getSapPackageList(String userId, String packageList, String spmsStatus) {
        packageList = StringUtils.isNotEmpty(packageList) ? packageList : null;
        spmsStatus = StringUtils.isNotEmpty(spmsStatus) ? spmsStatus : null;
        return this.baseMapper.getSapPackageList(userId, packageList, spmsStatus);
    }

    @Override
    public Page<Map<String, Object>> getSapPackageListPage(String userId, String packageList, String spmsStatus,
                                                           int pageNo, int pageSize) {
        pageNo = pageNo <= 0 ? 1 : pageNo;
        pageSize = pageSize <= 0 ? 20 : pageSize;
        packageList = StringUtils.isNotEmpty(packageList) ? packageList : null;
        spmsStatus = StringUtils.isNotEmpty(spmsStatus) ? spmsStatus : null;
        Page<Map<String, Object>> pages = new Page<>(pageNo, pageSize);
        List<Map<String, Object>> pageMaData = this.baseMapper.getSapPackageListPage(pages, userId, packageList, spmsStatus);
        pages.setRecords(pageMaData);
        return pages;
    }

    @Override
    public List<Map<String, Object>> getSapPackageListDtl(String packageList) {
        return iSapPackageListDtlService.getSapPackageList(packageList);
    }

    /***
     * @param userId
     * @param packageList
     * @param targetStatus
     * @param currentStatus
     * @return
     *
     * 1.更新装箱单表头。更新前该装箱单状态必须为 0待处理，否则不让更新；
     * 2.更新装箱单表表头状态为目标状态；
     * 3.更新装箱单明细表对应的行状态；
     * 4.装箱单更新成功后，执行 generateWhsOutTask 方法，按 装柜地点、货物类型、柜序号、可装柜日期 四个维度拆分出库任务；
     * 5.装箱单明细逐行遍历转换成出库任务：如果出库任务已经存在，则将该出库任务的 任务uuid 写入 装箱单明细对应行；
     *                                如果出库任务不存在，则新建一个出库任务，同时将 出库任务uuid 写入 装箱单明细对应行；
     * 6.记录装箱单操作日志；
     * 7.记录出库任务日志；
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized int updateSapPackageList(String userId, String packageList, String targetStatus, String currentStatus) {
        try {
            if (StringUtils.isEmpty(packageList) || StringUtils.isEmpty(targetStatus) || StringUtils.isEmpty(currentStatus)){
                return -1;
            }
            QueryWrapper<SapPackageList> queryWrapper = new QueryWrapper<SapPackageList>().eq("PACKAGE_LIST", packageList);
            SapPackageList sapPackageList = this.baseMapper.selectOne(queryWrapper);
            if (sapPackageList != null){
                /** 装箱单单据当前状态 跟前端 请求时的当前状态一致时才能执行更新操作；任务在SPMS状态(0待处理；1处理中；2处理完成)*/
                if (currentStatus.equals(sapPackageList.getSpmsStatus())){
                    SapPackageList sapPackageList1 = new SapPackageList();
                    sapPackageList1.setSpmsStatus(targetStatus);
                    /** 更新装箱单状态；更新装箱单行项目状态 */
                    int result =  this.baseMapper.update(sapPackageList1, queryWrapper);
                    iSapPackageListDtlService.updateSapPackageListDtl(packageList, targetStatus);
                    //记录 更新装箱单 日志
                    if ("1".equals(targetStatus)){
                        iSapDeliveryNoteLogService.insertSapDeliveryNoteLogM(packageList, userId, UPDATE_SAP_PACKAGE_LIST);
                    }
                    /** 当装箱单表头更新成功且目标状态 targetStatus 为 1 时，告知SAP装箱单已开始处理，调用装箱单上锁接口，生成出库任务及明细 */
                    if (result == 1 && "1".equals(targetStatus)){
                        JSONObject doc = lockSapPackageList(packageList);
                        iSapDeliveryNoteLogService.insertSapRequestRecord(packageList, userId, SAP_PACKAGE_LIST_LOCK,
                                doc.getJSONObject("sapReturnedData").toJSONString(), doc.getJSONObject("dataToSap").toJSONString());

                        generateWhsOutTask(packageList, userId);
                        //记录 装箱单生成出库任务 日志
                        iSapDeliveryNoteLogService.insertSapDeliveryNoteLogM(packageList, userId, SAP_PACKAGE_LIST_TO_WHS_OUT_TASK);
                    }
                    if ("2".equals(targetStatus)){
                        iSapDeliveryNoteLogService.insertSapDeliveryNoteLogM(packageList, userId, CLOSE_SAP_PACKAGE_LIST);
                    }
                    return result;
                }
            }
            return -2;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return -2;
        }
    }

    void generateWhsOutTask(String packageList, String userId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String createDate = sdf.format(new Date());
        List<Map<String, Object>> getSapPackageList = iSapPackageListDtlService.getSapPackageList(packageList);
        Set<String> whsLocationCodeSet = new HashSet<String>();
        Set<String> goodsTypeSet = new HashSet<String>();
        Set<String> cabinetSerialNumberSet = new HashSet<String>();
        Set<String> dateOfLoadingSet = new HashSet<String>();
        for (Map<String, Object> map : getSapPackageList){
            whsLocationCodeSet.add(map.get("loadingWhsLocationCode").toString());
            goodsTypeSet.add(map.get("goodsType").toString());
            cabinetSerialNumberSet.add(map.get("cabinetSerialNumber").toString());
            if (map.get("dateOfLoading") != null && StringUtils.isNotEmpty(map.get("dateOfLoading").toString())){
                dateOfLoadingSet.add(map.get("dateOfLoading").toString());
            }
        }
        for (Map<String, Object> sapPackageDtl : getSapPackageList){
            for (String whsLocationCode : whsLocationCodeSet){
                if (whsLocationCode.equals(sapPackageDtl.get("loadingWhsLocationCode"))){
                    for (String cabinetSerialNumber : cabinetSerialNumberSet){
                        if (cabinetSerialNumber.equals(sapPackageDtl.get("cabinetSerialNumber"))){
                            for (String dateOfLoading : dateOfLoadingSet){
                                if (dateOfLoading.equals(sapPackageDtl.get("dateOfLoading"))){
                                    for (String goodsType : goodsTypeSet){
                                        if (goodsType.equals(sapPackageDtl.get("goodsType"))){
                                            String werks = sapPackageDtl.get("loadingWerks").toString();
                                            WhsOut whsOut = iWhsOutService.getWhsOut(werks, whsLocationCode, packageList, goodsType, dateOfLoading, cabinetSerialNumber);
                                            /** 任务如果不存在则新建出库任务，更新装箱单明细 出库任务uuid 字段；如果存在则将该任务的 uuid 更新到装箱单明细 出库任务uuid 字段； */
                                            if (whsOut == null){
                                                String uuid = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();
                                                WhsOut whsOut1 = new WhsOut();
                                                whsOut1.setUuid(uuid);
                                                whsOut1.setWerks(werks);
                                                whsOut1.setWhsLocationCode(whsLocationCode);
                                                whsOut1.setPackageList(packageList);
                                                whsOut1.setGoodsType(goodsType);
                                                whsOut1.setDateOfLoading(dateOfLoading);
                                                whsOut1.setCabinetSerialNumber(cabinetSerialNumber);
                                                whsOut1.setCreateUserid(userId);
                                                whsOut1.setCreateDate(createDate);
                                                /** 给出库任务一个初始状态：0待执行 */
                                                whsOut1.setTaskStatus("0");
                                                iWhsOutService.insertWhsOut(whsOut1);

                                                /** 记录日志-出库任务初始化 */
                                                iSapDeliveryNoteLogService.insertSapDeliveryNoteLogM(uuid, userId, WHS_OUT_TASK_GENERATE);

                                                /** 将出库任务的 uuid 回写到 SAP装箱单任务明细 对应的行中 */
                                                iSapPackageListDtlService.updateSapPackageListDtl(packageList, sapPackageDtl.get("item").toString(), uuid);
                                            }else {
                                                /** 对已存在的出库任务，忽略新建出库任务，将已存在的出库任务uuid直接更新到 SAP装箱单明细表 行中 */
                                                iSapPackageListDtlService.updateSapPackageListDtl(packageList, sapPackageDtl.get("item").toString(), whsOut.getUuid());
                                            }
                                        }

                                    }

                                    /** 以下注释枚举贸易、备件货出库任务分发 */
//                                    String werks = sapPackageDtl.get("loadingWerks").toString();
//                                    String goodsType = sapPackageDtl.get("goodsType").toString();
//                                    if ("M".equals(sapPackageDtl.get("goodsType"))){
//                                        WhsOut whsOut = iWhsOutService.getWhsOut(werks, whsLocationCode, packageList, goodsType, dateOfLoading, cabinetSerialNumber);
//                                        /** 任务如果不存在则新建出库任务，更新装箱单明细 出库任务uuid 字段；如果存在则将该任务的 uuid 更新到装箱单明细 出库任务uuid 字段； */
//                                        if (whsOut == null){
//                                            String uuid = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();
//                                            WhsOut whsOut1 = new WhsOut();
//                                            whsOut1.setUuid(uuid);
//                                            whsOut1.setWerks(werks);
//                                            whsOut1.setWhsLocationCode(whsLocationCode);
//                                            whsOut1.setPackageList(packageList);
//                                            whsOut1.setGoodsType(goodsType);
//                                            whsOut1.setDateOfLoading(dateOfLoading);
//                                            whsOut1.setCabinetSerialNumber(cabinetSerialNumber);
//                                            whsOut1.setCreateDate(createDate);
//                                            /** 给出库任务一个初始状态：0待执行 */
//                                            whsOut1.setTaskStatus("0");
//                                            iWhsOutService.insertWhsOut(whsOut1);
//
//                                            /** 将贸易货出库任务的 uuid 回写到 SAP装箱单任务明细 对应的行中 */
//                                            iSapPackageListDtlService.updateSapPackageListDtl(packageList, sapPackageDtl.get("item").toString(), uuid);
//                                        } else {
//                                            System.out.println("该贸易货出库任务已存在：" + whsOut.toString());
//                                            /** 对已存在的贸易货出库任务，忽略新建出库任务，将已存在的出库任务uuid直接更新到 SAP装箱单明细表 行中 */
//                                            iSapPackageListDtlService.updateSapPackageListDtl(packageList, sapPackageDtl.get("item").toString(), whsOut.getUuid());
//                                        }
//                                    }else if ("X".equals(sapPackageDtl.get("goodsType"))){
//                                        WhsOut whsOut = iWhsOutService.getWhsOut(werks, whsLocationCode, packageList, goodsType, dateOfLoading, cabinetSerialNumber);
//                                        /** 任务如果不存在则新建出库任务，更新 装箱单箱码关系表 出库任务uuid 字段；如果存在则将该任务的 uuid 更新 装箱单箱码关系表 出库任务uuid 字段； */
//                                        if (whsOut == null){
//                                            String uuid = UUID.randomUUID().toString().replaceAll("-","").toLowerCase();
//                                            WhsOut whsOut1 = new WhsOut();
//                                            whsOut1.setUuid(uuid);
//                                            whsOut1.setWerks(werks);
//                                            whsOut1.setWhsLocationCode(whsLocationCode);
//                                            whsOut1.setPackageList(packageList);
//                                            whsOut1.setGoodsType(goodsType);
//                                            whsOut1.setDateOfLoading(dateOfLoading);
//                                            whsOut1.setCabinetSerialNumber(cabinetSerialNumber);
//                                            whsOut1.setCreateDate(createDate);
//                                            /** 给出库任务一个初始状态：0待执行 */
//                                            whsOut1.setTaskStatus("0");
//                                            iWhsOutService.insertWhsOut(whsOut1);
//
//                                            /** 将备件货出库任务的 uuid 回写到 装箱单箱码关系表 对应的行中 */
//                                            iSapPackageListDtlService.updateSapPackageListDtl(packageList, sapPackageDtl.get("item").toString(), uuid);
//                                        } else {
//                                            System.out.println("该备件货出库任务已存在：" + whsOut.toString());
//                                            /** 对已存在的备件货出库任务，忽略新建出库任务，将已存在的出库任务uuid直接更新到 装箱单箱码关系表 行中 */
//                                            iSapPackageListDtlService.updateSapPackageListDtl(packageList, sapPackageDtl.get("item").toString(), whsOut.getUuid());
//                                        }
//                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> getSapPackageListDtlM(String packageList) {
        return iSapPackageListDtlService.getSapPackageListDtlM(packageList);
    }

    @Override
    public JSONObject lockSapPackageList(String packageList) {
        if (StringUtils.isEmpty(packageList)){
            return null;
        }
        JSONObject dataToSap = formatDataToSapLock(packageList);
        JSONObject sapReturnedData = JSONObject.parseObject(iFeignServiceCommon.sendRestToSapCommon(dataToSap));
        JSONObject doc = new JSONObject();
        doc.put("dataToSap", dataToSap);
        doc.put("sapReturnedData", sapReturnedData);
        return doc;
    }

    @Override
    public ResponseResult getSapPackageListRest(String packageList) {
        try {
            if (StringUtils.isEmpty(packageList)){
                return ResponseResult.error("请求参数错误");
            }
            JSONObject dataToSap = formatDataToSapRest(packageList);
            JSONObject sapReturnedData = JSONObject.parseObject(iFeignServiceCommon.sendRestToSapCommon(dataToSap));
            JSONObject RETURN_DATA = sapReturnedData.getJSONObject("RESPONSE").getJSONObject("RETURN_DATA");
            if (StringUtils.isEmpty(RETURN_DATA.getString("O_TYPE")) || !"S".equals(RETURN_DATA.getString("O_TYPE"))){
                return ResponseResult.error().add("dataToSap", dataToSap).add("sapReturnedData", sapReturnedData);
            }
            return formatReturnedData(RETURN_DATA);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error().add("error", e.getMessage());
        }
    }

    JSONObject formatDataToSapRest(String packageList){
        JSONObject doc = new JSONObject();

        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();
        JSONObject REQUEST_DATA = new JSONObject();
        JSONObject Head = new JSONObject();

        ESB_ATTRS.put("App_ID", "SPMS");
        ESB_ATTRS.put("Application_ID", "00020000000002");
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString());

        Head.put("iXdnum", packageList);

        REQUEST_DATA.put("Head", Head);
        REQUEST_DATA.put("Operation", "Z_SPMS_CHECK_PL");
        REQUEST_DATA.put("Type", "CHECK_PL");

        REQUEST.put("ESB_ATTRS", ESB_ATTRS);
        REQUEST.put("REQUEST_DATA", REQUEST_DATA);

        doc.put("REQUEST", REQUEST);
        return doc;

    }

    JSONObject formatDataToSapLock(String packageList){
        JSONObject doc = new JSONObject();

        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();
        JSONObject REQUEST_DATA = new JSONObject();
        JSONObject Head = new JSONObject();

        ESB_ATTRS.put("App_ID", "SPMS");
        ESB_ATTRS.put("Application_ID", "00020000000002");
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString());

        Head.put("iXdnum", packageList);
        Head.put("iFlag", "X");

        REQUEST_DATA.put("Head", Head);
        REQUEST_DATA.put("Operation", "Z_SPMS_SET_ZXD_1120");
        REQUEST_DATA.put("Type", "SET_ZXD_1120");

        REQUEST.put("ESB_ATTRS", ESB_ATTRS);
        REQUEST.put("REQUEST_DATA", REQUEST_DATA);

        doc.put("REQUEST", REQUEST);
        return doc;
    }

    ResponseResult formatReturnedData(JSONObject doc){
        JSONObject sapPackageList = new JSONObject();
        JSONArray sapPackageListDtl = new JSONArray();
        JSONArray sapPackageListOperateRecord = new JSONArray();
        //装箱单表头信息，表头信息结构是数组，只会有一条
        JSONArray IT_ZXDTKO = doc.getJSONArray("IT_ZXDTKO");
        if (IT_ZXDTKO != null && IT_ZXDTKO.size() > 0){
            sapPackageList = getSapPackageList(IT_ZXDTKO.getJSONObject(0));
        }

        //装箱单表行项目信息
        JSONArray IT_ZXDTPO = doc.getJSONArray("IT_ZXDTPO");
        if (IT_ZXDTPO != null && IT_ZXDTPO.size() > 0){
            sapPackageListDtl = getSapPackageListDtl(IT_ZXDTPO);
        }

        //装箱单状态变化记录
        JSONArray IT_ZXDTSU = doc.getJSONArray("IT_ZXDTSU");
        if (IT_ZXDTSU != null && IT_ZXDTSU.size() > 0){
            sapPackageListOperateRecord = getSapPackageListOperateRecord(IT_ZXDTSU);
        }
        //暂不显示
        //JSONObject IT_TVKNT = doc.getJSONObject("IT_TVKNT");
        return ResponseResult.success().add("sapPackageList", sapPackageList)
                .add("sapPackageListDtl", sapPackageListDtl)
                .add("sapPackageListOperateRecord", sapPackageListOperateRecord);
    }

    JSONObject getSapPackageList(JSONObject IT_ZXDTKO){
        JSONObject doc = new JSONObject();
        doc.put("packageList", IT_ZXDTKO.getString("XDNUM"));
        doc.put("plannedCabinetsQty", IT_ZXDTKO.getString("PCONT"));
        doc.put("customer", IT_ZXDTKO.getString("KUNNR"));
        doc.put("spareParts", IT_ZXDTKO.getString("ZHBS"));
        doc.put("fromPort", IT_ZXDTKO.getString("SPORT"));
        doc.put("toPort", IT_ZXDTKO.getString("EPORT"));
        doc.put("shipCompany", IT_ZXDTKO.getString(""));
        doc.put("cabinetModel", IT_ZXDTKO.getString("MAGRV"));
        doc.put("createDate", IT_ZXDTKO.getString("CRDAT"));
        doc.put("actualCabinetQty",  IT_ZXDTKO.getString("ACONT"));
        doc.put("userId", IT_ZXDTKO.getString("SALE_USR"));
        return doc;
    }

    JSONArray getSapPackageListDtl(JSONArray IT_ZXDTPO){
        JSONArray doc = new JSONArray();
        for (int i = 0; i < IT_ZXDTPO.size(); i++){
            JSONObject dtl = IT_ZXDTPO.getJSONObject(i);
            JSONObject object = new JSONObject();
            String materialNo = dtl.getString("MATNR").replaceFirst("^0*", "");
            object.put("packageList", dtl.getString("XDNUM"));
            object.put("item", String.valueOf(Integer.parseInt(dtl.getString("POSNR").trim())));
            object.put("loadingWerks", dtl.getString("WERKS"));
            object.put("loadingWhsLocationCode", dtl.getString("LGORT"));
            object.put("cabinetSerialNumber", dtl.getString("CABIN"));
            object.put("materialNo", materialNo);
            object.put("basicUnit", dtl.getString("MEINS"));
            object.put("plannedPackingQty", dtl.getString("PMENG"));
            object.put("packingUnit", dtl.getString("VRKME"));
            object.put("plannedPackingNumber", dtl.getString("PEMNG"));
            object.put("actualOperateQty", dtl.getString("AMENG"));
            object.put("actualPackingNumber", dtl.getString("AEMNG"));
            object.put("directMark", dtl.getString("PKMAK"));

            Map<String, Object> materialSap = this.baseMapper.getNumeratorDenominator(materialNo);
            if (materialSap != null){
                object.put("numerator", Double.parseDouble(materialSap.get("numerator").toString()));
                object.put("denominator", Double.parseDouble(materialSap.get("denominator").toString()));
                object.put("materialZhDesc", materialSap.get("materialZhDesc").toString());
                object.put("materialEnDesc", materialSap.get("materialEnDesc").toString());
            }
            doc.add(object);
        }
        return doc;
    }

    JSONArray getSapPackageListOperateRecord(JSONArray IT_ZXDTSU){
        JSONArray doc = new JSONArray();
        for (int i = 0; i < IT_ZXDTSU.size(); i++){
            JSONObject item = IT_ZXDTSU.getJSONObject(i);
            JSONObject object = new JSONObject();
            object.put("packageList", item.getString("XDNUM"));
            object.put("linkSerialNumber", item.getString("SUINX"));    //环节序号
            object.put("operateStatus", item.getString("OPSTU"));   //操作状态
            object.put("currentStatus", item.getString("CURTU"));    //当前状态
            object.put("confirm", item.getString("CLRIM"));    //确认
            object.put("orderClose", item.getString("CLSTY"));    //订单关闭
            object.put("stepCancel", item.getString("XLZKE"));    //步骤取消
            object.put("operateDate", item.getString("DATUM"));    //日期
            object.put("operateTime", item.getString("UZEIT"));    //时间
            object.put("userId", item.getString("USERN"));    //用户
            object.put("type", item.getString("KTOKD"));    //类型
            doc.add(object);
        }
        return doc;
    }

    /**
     * 1.装箱单没有明细行（目前没发生），系统提示错误；
     * 2.装箱单明细 货物类型 字段为‘M’和‘X’以外的值 SAP_PACKAGE_LIST_DTL，系统提示错误（目前没发生）；
     * 3.装箱单备件明细行，没有装箱明细箱码关系数据 SAP_PACKAGE_BOX，系统提示错误；
     * 4.装箱单备件明细行，有装箱单明细箱码关系的情况下，再判断明细中的箱码在 箱码信息表 是否存在，不存在则系统提示错误（目前没发生）；
     * 5.装箱单贸易货明细行，如果存在装箱单明细箱码关系 SAP_PACKAGE_BOX，系统提示错误；
     * */
    @Override
    public ResponseResult checkSapPackageListCanBeSplit(String packageList) {
        if (StringUtils.isEmpty(packageList)){
            return ResponseResult.error("请求参数错误请重试");
        }
        SapPackageList sapPackageList = this.baseMapper.selectOne(new QueryWrapper<SapPackageList>().eq("PACKAGE_LIST", packageList));
        if (sapPackageList == null){
            return ResponseResult.error("装箱号单查询不存在");
        }
        if (!"0".equals(sapPackageList.getSpmsStatus())){
            return ResponseResult.error("装箱单(SAP_PACKAGE_LIST)状态为 已拆分 或 已完成，不能拆分出库任务");
        }
        List<SapPackageListDtl> dtlList = sapPackageListDtlMapper.selectList(new QueryWrapper<SapPackageListDtl>().eq("PACKAGE_LIST", packageList));
        if (dtlList == null || dtlList.size() == 0){
            return ResponseResult.error("装箱单明细数据(SAP_PACKAGE_LIST_DTL)缺失，数据错误不能拆分出库任务");
        }
        for (int i = 0; i < dtlList.size(); i++){
            SapPackageListDtl dtl = dtlList.get(i);
            String dtlPackageList = dtl.getPackageList();
            String item = dtl.getItem();
            QueryWrapper<SapPackageBox> boxQueryWrapper = new QueryWrapper<SapPackageBox>().eq("PACKAGE_LIST", dtlPackageList).eq("ITEM", item);
            if ("M".equals(dtl.getGoodsType())){
                List<SapPackageBox> boxList = sapPackageBoxMapper.selectList(boxQueryWrapper);
                if (boxList != null && boxList.size() > 0){
                    return ResponseResult.error("装箱单" + dtlPackageList + " 贸易货行号 " + item + " 存在箱码信息(SAP_PACKAGE_LIST_DTL, SAP_PACKAGE_BOX)，数据错误无法拆分出库任务")
                            .add("sapPackageList", sapPackageList.toString())
                            .add("sapPackageListDtl", dtl.toString())
                            .add("sapPackageBox", boxList.toString());
                }
            } else if ("X".equals(dtl.getGoodsType())){
                List<SapPackageBox> boxList = sapPackageBoxMapper.selectList(boxQueryWrapper);
                if (boxList == null || boxList.size() == 0){
                    return ResponseResult.error("装箱单" + dtlPackageList + " 备件货行号 " + item + " 不存在装箱单明细箱码关系数据(SAP_PACKAGE_LIST_DTL, SAP_PACKAGE_BOX)，数据错误无法拆分出库任务")
                            .add("sapPackageList", sapPackageList.toString())
                            .add("sapPackageListDtl", dtl.toString())
                            .add("sapPackageBox", boxList);
                } else {
                    for (int j = 0; j < boxList.size(); j++){
                        SapPackageBox sapPackageBox = boxList.get(j);
                        String boxNote = sapPackageBox.getBoxNote();
                        if (StringUtils.isEmpty(boxNote)){
                            return ResponseResult.error("装箱单" + dtlPackageList + " 备件货行号 " + item + " 装箱单明细箱码关系数据中箱码信息错误(SAP_PACKAGE_BOX)，数据错误无法拆分出库任务")
                                    .add("sapPackageList", sapPackageList.toString())
                                    .add("sapPackageListDtl", dtl.toString())
                                    .add("sapPackageBox", sapPackageBox);
                        }
                        SapBoxNote sapBoxNote = iSapBoxNoteService.getByBoxNote(boxNote);
                        if (sapBoxNote == null){
                            return ResponseResult.error("装箱单" + dtlPackageList + " 备件货行号 " + item + " 装箱单明细箱码关系数据中箱码存在(SAP_PACKAGE_LIST_DTL, SAP_PACKAGE_BOX)，但箱码在箱码信息表(SAP_BOX_NOTE)中数据不存在，数据错误无法拆分出库任务")
                                    .add("sapPackageList", sapPackageList.toString())
                                    .add("sapPackageListDtl", dtl.toString())
                                    .add("sapPackageBox", sapPackageBox)
                                    .add("boxNote", boxNote);
                        }
                    }
                }
            } else {
                return ResponseResult.error("装箱单明细数据(SAP_PACKAGE_LIST_DTL)不合要求，数据错误无法拆分出库任务")
                        .add("sapPackageList", sapPackageList.toString())
                        .add("sapPackageListDtl", dtl.toString());
            }
        }
        return ResponseResult.success("数据正确，能进行出库任务拆分");
    }
}
